require "digest/sha1"

#fields:email, password, state, security_string
class User < ActiveRecord::Base
  
  attr :password_again,true
  
#  REGISTER_URL="http://ics.pidgincn.com/manage/register"
  REGISTER_URL="http://localhost:3000/manage/register"

  STATE_UNCHECK=0
  STATE_ENABLED=1

  REGISTER_COMMAND="注册"

  NO_PASSWORD="NOPASSWORD"

  validates_presence_of :email,:password,:state
  validates_uniqueness_of :email

  def self.find_uncheck_by_security(security_string)
    User.find(:first,:conditions=>{:security_string=>security_string,:state=>STATE_UNCHECK})
  end
  
  def self.get_register_user(email)
    User.find :first,:conditions=>["email=? and state=?",email,STATE_ENABLED]
  end
  
  def self.safe_get_user(email)
    u=User.find :first,:conditions=>["email=?",email]
    if u==nil
      u=User.new(:email=>email,:password=>NO_PASSWORD,:state=>STATE_UNCHECK)
      u.save!
    end
    u
  end
  
  def self.unregister_message()
    "未注册用户，请输入命令“#{REGISTER_COMMAND}”"
  end
  
  def self.get_register_url(email)
    user=safe_get_user(email) 
    user.generate_security_string
#    user.save!
    "#{REGISTER_URL}/#{user.security_string}"
  end

  def self.register_command?(cmd)
    REGISTER_COMMAND == cmd.to_s().strip()
  end
  
  def generate_security_string
    self.security_string=Digest::SHA1.hexdigest("#{self.email}#{rand}")
    User.update_all("security_string='#{self.security_string}'",["id=?",self.id])
  end

  def enable
    self.state=STATE_ENABLED
    User.update_all("state=#{STATE_ENABLED}",["id=?",self.id])
  end

end
